<?php

namespace Hx\Mvc\View;

use Hx\App;
use Hx\Di;

/**
 * Class View
 * @property \Hx\Http\Response response
 * @package Hx\Mvc
 */
class Simple extends Di implements Base {

    /**
     * 视图目录
     * @var string
     */
    private $path;

    /**
     * 模板文件后缀名
     * @var string
     */
    private $suffix;

    /**
     * 模板文件绝对地址
     * @var string
     */
    private $template;

    /**
     * 构造方法
     * @param array $config 配置信息
     */
    public function __construct($config) {
        $this->path = App::getInstance()->getPath() . $config['path'];
        $this->suffix = !isset($config['suffix']) ? 'php' : $config['suffix'];
        $this->data = array(
            'baseUrl' => App::getInstance()->getClass('\Hx\Http\Request')->baseUrl
        );
    }

    /**
     * 设置模板
     * @param string $template
     * @return $this
     */
    public function setTemplate($template) {
        $file = $this->path . $template . '.' . $this->suffix;
        if (!is_file($file)) {
            #模板无效，抛出错误
            App::error('no template file : ' . $template);
        }
        $this->template = $file;
        return $this;
    }

    /**
     * 判断模板是否存在
     * @param string $template
     * @return bool
     */
    public function hasTemplate($template){
        $file = $this->path . $template . '.' . $this->suffix;
        return is_file($file);
    }

    /**
     * 视图数据
     * @var array
     */
    private $data = array();

    /**
     * 添加视图数据
     * @param string|array $key
     * @param mixed|null $value
     * @return $this
     */
    public function assign($key, $value = NULL) {
        if ($value !== NULL) {
            $this->data[$key] = $value;
            return $this;
        }
        foreach ($key as $k => $v) {
            $this->assign($k, $v);
        }
        return $this;
    }

    /**
     * 显示视图
     * 会发送请求
     */
    public function display() {
        $content = $this->parse();
        $this->set('response', 'Hx\Http\Response');
        $this->response->setBody($content);
        $this->response->send();
    }

    /**
     * 解渲染视图
     * @return string
     */
    public function parse() {
        if (!$this->template) {
            App::error('no template file');
        }
        ob_start();
        extract($this->data);
        include $this->template;
        return ob_get_clean();
    }


}